
// 公众号音源

import {
  createCustomAlovaInstance
} from '../ApiRequest'
import type { Method } from 'alova'

const APP_INFO = {
  version: '2.11.0',
  env: 'desktop'
}

class Ikun2 {
  private API_URL = 'https://music.ikun0014.top'
  private API_KEY = ''
  private ResponseKey = 'url'
  private alovaInstance = createCustomAlovaInstance({
    beforeRequest: (_: Method) => {
    },
    onSuccess: async (response) => {
      const status = response.status
      const clonedResponse = response.clone()
      if (response.status === 200 || response.status === 304) {
        try {
          const data: {
            code: number
            data: string
            msg: string
            [key: string]: unknown
          } = await response.json()
          if (!data || isNaN(Number(data.code))) throw new Error('unknow error')
          switch (Number(data.code)) {
            case 200:
              return data[this.ResponseKey]
            case 1:
              throw new Error('blocked ip')
            case 2:
              throw new Error('get music url failed')
            case 4:
              throw new Error('internal server error')
            case 5:
              throw new Error('too many requests')
            case 6:
              throw new Error('invalid params')
            default:
              throw new Error(data.msg ?? 'unknow error')
          }
        } catch {
          return clonedResponse
        }
      } else if (status >= 400 && status < 600) {
        // 请求失败处理
        throw new Error(response.statusText)
      } else {
        throw new Error((await response.json()).message)
      }
    },
    onError: (error: Error) => {
      throw error
    },
    onComplete: () => {},
  })
  public MUSIC_QUALITY = {
    'kw': ['128k', '320k', 'flac', 'flac24bit', 'hires'],
    'kg': ['128k', '320k', 'flac', 'flac24bit', 'hires'],
    'tx': ['128k', '320k', 'flac', 'flac24bit', 'hires'],
    'wy': ['128k', '320k', 'flac', 'flac24bit', 'hires'],
    'mg': ['128k', '320k', 'flac', 'flac24bit', 'hires'],
  }
  public MUSIC_SOURCE = Object.keys(this.MUSIC_QUALITY).concat(['local'])

  async getMusicUrl(id: string, source: string, quality: string): Promise<string> {
    return this.alovaInstance.Get(`${this.API_URL}/url?songId=${id}&source=${source}&quality=${quality}`, {
      headers: {
        // 'Content-Type': 'application/json',
        'User-Agent': APP_INFO.env ? `lx-music-${APP_INFO.env}/${APP_INFO.version}` : `lx-music-request/${APP_INFO.version}`,
        // 'X-Request-Key': this.API_KEY
      }
    })
  }
}

export default Ikun2
